using UnityEngine;

namespace GameCore
{
    public class PlaceGridItemState : PlayerInputState
    {
        public Inventory sourceInventory;
        public Vector2Int gridPos;
        public GridItem holding;
        public Cell SimpleCell;

        public PlaceGridItemState(GridItem gridItem)
        {
            holding = gridItem;
            sourceInventory = gridItem.parentInventory;
            gridPos = gridItem.gridPos;
        }

        public override void Init(PlayerInputHandler handler)
        {
            sourceInventory.RemoveItem(holding.gridPos);
        }

        public override void OnHoveringCellChanged(Cell prev, Cell curr)
        {
            prev?.inventory.ClearPreview();
            curr?.inventory.PreviewPlaceItem(holding, curr.gridPos);
            SimpleCell = curr;
        }

        public override void Update()
        {
            var mousePos = PlayerInputHandler.GetMouseWorldPosition();
            holding.transform.position = new Vector3(mousePos.x - 0.5f, mousePos.y - 0.5f, -1);
            if (Input.GetMouseButtonDown(0))
            {
                if (SimpleCell is null) return;
                PlayerInputHandler.ApplyPlaceGridItem();
            }
            else if (Input.GetMouseButtonDown(1))
            {
                PlayerInputHandler.CancelPlaceGridItem();
            }
        }

        public override void Apply()
        {
            if (SimpleCell.inventory.ValidatePlaceItem(SimpleCell.gridPos, holding))
            {
                SimpleCell.PlaceItem(holding);
            }
            else
            {
                sourceInventory.PlaceItem(gridPos, holding);
            }
        }

        public override void Cancel()
        {
            sourceInventory.PlaceItem(gridPos, holding);
        }

        public override void Exit()
        {
            SimpleCell?.inventory.ClearPreview();
        }
    }
}